package com.maycari.captainbi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.maycari.captainbi.data.dto.AuthorizationManagementDto;
import com.maycari.captainbi.data.dto.SyncRecordDto;
import com.maycari.captainbi.data.po.AuthorizationManagementPo;
import com.maycari.captainbi.data.po.SyncRecordPo;
import com.maycari.captainbi.mapper.SyncRecordDao;
import com.maycari.captainbi.service.SyncRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maycari.tool.utils.BeanUtil;
import com.maycari.tool.utils.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 同步记录表 服务实现类
 * </p>
 *
 * @author 王宏伟
 * @since 2021-04-12
 */
@Service
public class SyncRecordServiceImpl extends ServiceImpl<SyncRecordDao, SyncRecordPo> implements SyncRecordService {

    @PostConstruct
    void init() {
        System.out.println(1);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insert(SyncRecordDto syncRecordDto) {
        SyncRecordPo po = getById(syncRecordDto.getId());
        if (po == null) {
            po = BeanUtil.copy(syncRecordDto, SyncRecordPo.class);
            po.setCreateTime(new Date());
            save(po);
        } else {
            Integer syncCount = po.getSyncCount();
            Integer status = syncRecordDto.getStatus();
            if (status == 1) {
                po.setStatus(status);
                po.setMsg("");
            } else {
                if (syncCount >= 9) {
                    po.setStatus(2);
                } else {
                    po.setStatus(status);
                }
                String msg = syncRecordDto.getMsg();
                if (StringUtil.isNotBlank(msg) && msg.length() > 900) {
                    msg = msg.substring(0, 900);
                }
                po.setMsg(msg);
            }
            po.setSyncCount(syncCount + 1);
            po.setModifyTime(new Date());
            updateById(po);
        }
        return po.getId();
    }

    @Override
    public List<SyncRecordDto> getAllExceptionRecord() {
        LambdaQueryWrapper<SyncRecordPo> la = new LambdaQueryWrapper<>();
        la.eq(SyncRecordPo::getStatus, 0);
        la.le(SyncRecordPo::getSyncCount,9);
        return BeanUtil.copy(baseMapper.selectList(la), SyncRecordDto.class);
    }

    @Override
    public SyncRecordDto getSyncRecordDtoById(String syncRecordId) {
        SyncRecordPo po = getById(syncRecordId);
        return BeanUtil.copy(po, SyncRecordDto.class);
    }


}
